<template>
  <el-dialog
    v-model="dialogVisible"
    title="活动详情"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading" class="detail-container">
      <template v-if="activityDetail">
        <!-- 图片轮播 -->
        <div class="image-carousel" v-if="activityDetail.images && activityDetail.images.length > 0">
          <el-carousel height="300px" indicator-position="outside">
            <el-carousel-item v-for="(img, index) in activityDetail.images" :key="index">
              <el-image :src="img" fit="cover" style="width: 100%; height: 100%" />
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 活动信息 -->
        <div class="detail-content">
          <h2 class="detail-title">{{ activityDetail.title }}</h2>

          <!-- 状态标签 -->
          <div class="detail-status">
            <el-tag v-if="activityDetail.status === 0" type="success">未开始</el-tag>
            <el-tag v-else-if="activityDetail.status === 1" type="warning">进行中</el-tag>
            <el-tag v-else type="info">已结束</el-tag>
          </div>

          <!-- 详细信息 -->
          <div class="detail-info">
            <div class="info-item">
              <label>活动简介：</label>
              <span>{{ activityDetail.description }}</span>
            </div>
            <div class="info-item">
              <label>活动地点：</label>
              <span>{{ activityDetail.location }}</span>
            </div>
            <div class="info-item">
              <label>开始时间：</label>
              <span>{{ formatDateTime(activityDetail.startTime) }}</span>
            </div>
            <div class="info-item">
              <label>结束时间：</label>
              <span>{{ formatDateTime(activityDetail.endTime) }}</span>
            </div>
            <div class="info-item">
              <label>人数限制：</label>
              <span>
                {{ activityDetail.currentParticipants }}/{{ activityDetail.maxParticipants === 0 ? '不限' : activityDetail.maxParticipants }}
                <el-tag v-if="isFull" type="danger" size="small" style="margin-left: 10px">已满员</el-tag>
              </span>
            </div>
            <div class="info-item">
              <label>发布者：</label>
              <span>{{ activityDetail.publisherName }}</span>
            </div>
          </div>

          <!-- 报名表单 -->
          <div class="enroll-form" v-if="!isEnrolled">
            <el-form :model="enrollForm" label-width="80px">
              <el-form-item label="联系方式">
                <el-input
                  v-model="enrollForm.contactInfo"
                  placeholder="请输入您的联系方式（选填）"
                  maxlength="100"
                />
              </el-form-item>
            </el-form>
          </div>

          <!-- 已报名提示 -->
          <el-alert
            v-if="isEnrolled"
            title="您已成功报名此活动"
            type="success"
            :closable="false"
            show-icon
          />
        </div>
      </template>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="hasActivityAuditPermission('activity:audit')"
          type="warning"
          @click="handleEdit"
        >
          修改活动
        </el-button>
        <el-button
          v-if="!isEnrolled"
          type="primary"
          :loading="enrollLoading"
          :disabled="!canEnroll"
          @click="handleEnroll"
        >
          {{ enrollButtonText }}
        </el-button>
        <el-button
          v-if="isEnrolled"
          type="danger"
          :loading="cancelLoading"
          @click="handleCancelEnroll"
        >
          取消报名
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { reqGetActivityDetail, reqEnrollActivity, reqCancelEnroll, reqCheckEnrollStatus } from '@/api/activity'
import type { ActivityItem } from '@/api/activity/type'
import useUserStore from '@/stores/modules/user'
import dayjs from 'dayjs'

// 获取用户信息
const userStore = useUserStore()

const props = defineProps<{
  modelValue: boolean
  activityId: number
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
  (e: 'edit', activityId: number): void
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const enrollLoading = ref(false)
const cancelLoading = ref(false)
const activityDetail = ref<ActivityItem | null>(null)
const isEnrolled = ref(false)

const enrollForm = ref({
  contactInfo: ''
})

// 是否已满员
const isFull = computed(() => {
  if (!activityDetail.value) return false
  if (activityDetail.value.maxParticipants === 0) return false
  return activityDetail.value.currentParticipants >= activityDetail.value.maxParticipants
})

// 是否可以报名
const canEnroll = computed(() => {
  if (!activityDetail.value) return false
  if (activityDetail.value.status === 2) return false // 已结束
  if (isFull.value) return false // 已满员
  return true
})

const hasActivityAuditPermission = (perm: string) => {
  return userStore.buttons.includes(perm)
}

// 报名按钮文本
const enrollButtonText = computed(() => {
  if (!activityDetail.value) return '报名'
  if (activityDetail.value.status === 2) return '活动已结束'
  if (isFull.value) return '名额已满'
  return '立即报名'
})

// 获取活动详情
const getActivityDetail = async () => {
  if (!props.activityId || loading.value) return
  loading.value = true

  try {
    const result: any = await reqGetActivityDetail(props.activityId)
    if (result.code === 200) {
      activityDetail.value = result.data

      // 检查是否已报名
      await checkEnrollStatus()
    } else {
      ElMessage.error(result.message || '获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 检查报名状态
const checkEnrollStatus = async () => {
  try {
    const result: any = await reqCheckEnrollStatus(props.activityId)
    if (result.code === 200) {
      isEnrolled.value = result.data.enrolled || false
    }
  } catch (error) {
    console.error('检查报名状态失败:', error)
  }
}

// 报名
const handleEnroll = async () => {
  if (!canEnroll.value) {
    if (isFull.value) {
      ElMessage.error('名额已满，无法报名')
    } else if (activityDetail.value?.status === 2) {
      ElMessage.error('活动已结束，无法报名')
    }
    return
  }

  enrollLoading.value = true

  try {
    const result: any = await reqEnrollActivity({
      activityId: props.activityId,
      contactInfo: enrollForm.value.contactInfo
    })

    if (result.code === 200) {
      ElMessage.success('报名成功！')
      isEnrolled.value = true
      emit('refresh')

      // 刷新活动详情
      await getActivityDetail()
    } else {
      ElMessage.error(result.message || '报名失败')
    }
  } catch (error: any) {
    console.error('报名失败:', error)
    ElMessage.error(error.message || '报名失败')
  } finally {
    enrollLoading.value = false
  }
}

// 取消报名
const handleCancelEnroll = async () => {
  cancelLoading.value = true

  try {
    const result: any = await reqCancelEnroll(props.activityId)

    if (result.code === 200) {
      ElMessage.success('已取消报名')
      isEnrolled.value = false
      emit('refresh')

      // 刷新活动详情
      await getActivityDetail()
    } else {
      ElMessage.error(result.message || '取消报名失败')
    }
  } catch (error) {
    console.error('取消报名失败:', error)
    ElMessage.error('取消报名失败')
  } finally {
    cancelLoading.value = false
  }
}

// 修改活动
const handleEdit = () => {
  if (activityDetail.value) {
    emit('edit', activityDetail.value.id)
    handleClose()
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
  activityDetail.value = null
  isEnrolled.value = false
  enrollForm.value.contactInfo = ''
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
}

// 监听对话框打开
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.activityId) {
    getActivityDetail()
  }
})
</script>

<style scoped lang="scss">
.detail-container {
  min-height: 300px;
}

.image-carousel {
  margin-bottom: 20px;

  :deep(.el-carousel__item) {
    background-color: #f5f7fa;
  }
}

.detail-content {
  .detail-title {
    margin: 0 0 15px;
    font-size: 24px;
    font-weight: 600;
  }

  .detail-status {
    margin-bottom: 20px;
  }

  .detail-info {
    margin-bottom: 20px;

    .info-item {
      display: flex;
      margin-bottom: 15px;
      line-height: 1.8;

      label {
        min-width: 80px;
        font-weight: 600;
        color: #606266;
      }

      span {
        flex: 1;
        color: #303133;
      }
    }
  }

  .enroll-form {
    margin-top: 30px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

